#include "SockConnection.h"
#include "SocketListener.h"

using namespace OOPNetwork;
using namespace OOPUtils;




SockConnection::SockConnection (SocketListener & listener, SOCKET socket,
  sockaddr_in clientAddr) : _listener (listener), _socket (socket),
  _clientAddr (_clientAddr), _bufferSize (MAX_BUFFER_SIZE)
{
  _buffer = new char[_bufferSize];
}



SockConnection::~SockConnection ()
{
  closeConnection ();
  delete [] _buffer;
}



void SockConnection::sendData (const ByteStream & data) const
{
  if (
    send (_socket, data.getBytes (), data.getLength (), 0) == SOCKET_ERROR)
    throw ("Send Error.");
}



PtrBase< ByteStream > SockConnection::receiveData () const
{
  int lengthReceived = recv (_socket, _buffer, _bufferSize, 0);
  if (lengthReceived <= 0)
    throw ("Client has exited.");

  return new ByteStream (_buffer, (size_t) lengthReceived);
}



void SockConnection::closeConnection () const
{
  closesocket (_socket);
}

string SockConnection::getClientIP () const
{
  return inet_ntoa (_clientAddr.sin_addr);
}

unsigned int SockConnection::getClientPort () const
{
  return _clientAddr.sin_port;
}
